﻿using AutoMapper;
using B.S.ProcessEgine.API.Applocations.Commands.FormInfoCommand;
using B.S.ProcessEgine.Domain.Entities;
using B.S.ProcessEgine.ErrorCode;
using B.S.ProcessEgine.Infractructure.Interfaces;
using MediatR;

namespace B.S.ProcessEgine.API.Applocations.CommandHandlers.FormInfo
{

    public class FormUpdateCommandHandler : IRequestHandler<FormUpdateCommand, ApiResult>
    {
        private readonly IFormInfoRepository _formRepository;
        private readonly ILogger<FormUpdateCommandHandler> _logger;
        private readonly IMapper _mapper;

        public FormUpdateCommandHandler(IFormInfoRepository formRepository, ILogger<FormUpdateCommandHandler> logger, IMapper mapper)
        {
            _formRepository = formRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult> Handle(FormUpdateCommand request, CancellationToken cancellationToken)
        {
            try
            {
               /* var form = await _formRepository.GetAsync(x => x.FormId == request.Info.FormId && !x.IsDel);

                if (form == null)
                {
                    return ApiResult.Fail("对象不存在", StateCodeEnum.Fail);
                }*/

                //更新表单
                //var formTypeInfo = _mapper.Map<Domain.Entities.FormInfo>(request.Info);

                var result = await _formRepository.UpdateAsync(request.Info);

                return result > 0 ? ApiResult.Success(StateCodeEnum.Ok) : ApiResult.Fail("更新表单失败", StateCodeEnum.Fail);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "FormUpdateCommandHandler Error");
                return ApiResult.Fail("更新表单异常", StateCodeEnum.Exception);
            }
        }
    }

    }
